package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.item.constants.MqConstants;
import com.hmall.item.pojo.Item;

import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public void updateStatus(Long id, Integer status) {
        this.update().set("status", status).eq("id", id).update();

        String routingKey = status == 1 ? MqConstants.ITEM_INSERT_KEY : MqConstants.ITEM_DELETE_KEY;
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, routingKey, id);
    }

    @Override
    public void deduct(Long itemId, Integer num) {
        Item item = this.getById(itemId);
        this.update().set("stock", item.getStock() - num).eq("id", itemId).update();
    }
}
